package jse.io;

import jse.io.filter.DirFilter;
import org.junit.Test;

import java.io.File;
import java.io.IOException;

/**
 * @desc 测试file类
 * @author kanggw
 * @create 2016 08 11 8:34
 */
public class TestFile {

    @Test
    public void test() throws IOException{

      /*  String path = "c:" + File.separator + "test";
        File file = new File(path);
        File[] files = file.listFiles(new DirFilter("java"));
        for(int i = 0;i<files.length;i++) {
            System.out.println(files[i]);
        }*/
        String path = "c:" + File.separator + "test";
        File file = new File(path);
        this.listAllPosterity(file);

        }

    /**
     * @desc 获取路径下所有文件夹及文件
     * @param path
     * @author kanggw
     * @creatTime 2016-8-11 10:38:59
     */
    public void listAllFilesAndDirs(String path) {

        File file = new File(path);
        for(int i =0 ;i<file.list().length;i++ ) {
            System.out.println(file.list()[i]);
        }
    }

    /**
     * @desc 获取路径下所有文件夹及文件，并按照文件类型区分
     * @param path
     * @author kanggw
     * @creatTime 2016-8-11 10:38:59
     */
    public void listAllFilesAndDirsDis(String path) {

        File file = new File(path);
        for(int i =0 ;i<file.list().length;i++ ) {
            File file1 = new File(path + File.separator + file.list()[i]);
            if (file1.isFile()) {
                System.out.println(file.list()[i]);
            }
        }
        for(int i =0 ;i<file.list().length;i++ ) {
            File file1 = new File(path + File.separator + file.list()[i]);
            if (file1.isDirectory()) {
                System.out.println(file.list()[i]);
            }
        }
    }

    /**
     * @desc 获取路径下所有子孙文件及子孙目录名称
     * @author kanggw
     * @creatTime 2016-8-11 10:38:59
     */
    public void listAllPosterity(File file) {

        //判断是否是路径，如果是则继续调用次方法
        if (file.isDirectory()) {
            System.out.println(file.getName());
            //得到路径下文件及目录名称
            String[] list = file.list();
            for (int i = 0; i < list.length; i++) {
                File file1 = new File(file.getPath() + File.separatorChar + list[i]);
                this.listAllPosterity(file1);
            }

        } else {//不是路径则打印名称
            System.out.println(file.getName());
        }
    }
}

